package com.helen.ui.userinfo;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.coorchice.library.SuperTextView;
import com.helen.db.UserHelper;
import com.helen.entity.LoginRegisterEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.login.LoginActivity;
import com.helen.utils.ActivityHelper;
import com.helen.utils.MD5;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.SharedPreferencesUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.MyEditText;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/26.
 * 修改绑定手机号
 */

public class UpdateBindPhoneActivity extends BaseActivity {
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.et_phone)
    MyEditText etPhone;
    @BindView(R.id.et_sms_code)
    EditText etSmsCode;
    @BindView(R.id.tv_get_sms_code)
    TextView tvGetSmsCode;
    @BindView(R.id.tv_bind)
    SuperTextView tvBind;
    private LoginRegisterEntity loginRegisterEntity;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_update_bind_phone;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.update_bind_phone);
        loginRegisterEntity = UserHelper.getInstance().getloginEntity(UpdateBindPhoneActivity.this);
        if (loginRegisterEntity != null) {
            tvPhone.setText(loginRegisterEntity.getPhone());
        }
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.tv_get_sms_code, R.id.tv_bind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_sms_code:
                String phoneCode = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phoneCode)) {
                    MToast.makeTextShort(UpdateBindPhoneActivity.this, "手机号不能为空").show();
                    etPhone.requestFocus();
                    return;
                }

                if (!PhoneUtils.isMobileNO(phoneCode)) {
                    MToast.makeTextShort(UpdateBindPhoneActivity.this, "手机号格式错误").show();
                    etPhone.requestFocus();
                    return;
                }

                getMsgCodeApi(phoneCode);
                break;
            case R.id.tv_bind:
                String phoneCode2 = etPhone.getText().toString().trim();
                String code = etSmsCode.getText().toString().trim();
                if (TextUtils.isEmpty(phoneCode2)) {
                    MToast.makeTextShort(UpdateBindPhoneActivity.this, "手机号不能为空").show();
                    etPhone.requestFocus();
                    return;
                }

                if (!PhoneUtils.isMobileNO(phoneCode2)) {
                    MToast.makeTextShort(UpdateBindPhoneActivity.this, "手机号格式错误").show();
                    etPhone.requestFocus();
                    return;
                }

                if (TextUtils.isEmpty(code)) {
                    MToast.makeTextShort(UpdateBindPhoneActivity.this, "验证码不能为空").show();
                    etSmsCode.requestFocus();
                    return;
                }
                bindPhone(phoneCode2, code);

                break;
        }
    }


    private void bindPhone(String phone, String code) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(UpdateBindPhoneActivity.this).getId());
        params.put("phone", phone);
        params.put("code", code);
        EasyHttp.post(Constants.API_JSONAPI_BINDPHONE)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "绑定手机号失败==" + e.toString());
                        MToast.makeTextShort(UpdateBindPhoneActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(UpdateBindPhoneActivity.this, result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(UpdateBindPhoneActivity.this, "修改成功,请重新登录").show();
//                            SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_AUTH_KEY_STORAGE);
//                            SharedPreferencesUtils.remove(UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_LOGIN_MODEL);
                            ActivityHelper.getInstance().finishAllActivity();
                            UserHelper.getInstance().setloginEntity(UpdateBindPhoneActivity.this, null);
                            UserHelper.getInstance().setIsLogined(false);
                            startActivity(new Intent(UpdateBindPhoneActivity.this, LoginActivity.class));
                        }
                    }
                });
    }


    //    获取验证码接口
    private void getMsgCodeApi(String phone) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", phone);
        params.put("key", MD5.getMD5Str(phone + "888888").toUpperCase());
        EasyHttp.post(Constants.API_JSONAPI_SMS_CODE)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "获取验证码失败==" + e.toString());
                        MToast.makeTextShort(UpdateBindPhoneActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(UpdateBindPhoneActivity.this, result, TAG);
                        if (data != null) {
                            timer.start();
                        }
                    }
                });
    }


    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvGetSmsCode.setClickable(false);// 设置不能点击
            tvGetSmsCode.setText(millisUntilFinished / 1000 + "秒后重新发送");// 设置倒计时时间
            tvGetSmsCode.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
        }

        @Override
        public void onFinish() {
            tvGetSmsCode.setText(getResources().getString(R.string.get_sms_code));
            tvGetSmsCode.setClickable(true);// 重新获得点击
            tvGetSmsCode.setTextColor(getResources().getColor(R.color.appThemeColor));

        }
    };

}
